import React from 'react';
import { toJS } from 'mobx';
import { inject, observer, } from 'mobx-react';
import { Route, withRouter, Redirect } from 'react-router-dom';
import { Tools, Modal, Tabs, Select, Flex, List, Checkbox, SearchBar, WingBlank, Button, WhiteSpace, Switch, } from 'weaver-mobile';
import { Form, } from 'weaver-mobile-page';

import BreadCrumb from '../home/breadcrumb';

const CheckboxItem = Checkbox.CheckboxItem;
const getLabel = Tools.getLabel;


@withRouter
@inject('homeStore')
@observer
export default class DeatilSetting extends React.Component {
  static defaultProps = {
    prefixCls: 'msg-setting-home',
  }

  constructor(props) {
    super(props);
    this.bottomSave = this.bottomSave.bind(this);
  }

  componentDidMount() {
    const { homeStore, prefixCls, history } = this.props;
    const { detailSettingForm } = homeStore;
    document.title = getLabel("19342", "详细设置");
    homeStore.dataChange = false;
    if (!detailSettingForm.conditioninfo[0]) {
      history.push("/home/sublist")
    }
  }

  syncClick(e) {
    const { homeStore } = this.props;
    const { detailSetting } = homeStore;
    homeStore.dataChange = true;
    detailSetting.syncModal = true;
  }

  syncConfirm() {
    const { homeStore } = this.props;
    homeStore.dataChange = true;
    const { detailSetting, detailSettingForm } = homeStore;
    const JSONFormParams = JSON.parse(JSON.stringify((detailSettingForm.formData)));
    let updateFields = JSONFormParams;

    const currentKey = detailSetting.tabIndex;
    const gotoSync = detailSettingForm.conditioninfo[0].syncValue.split(",");
    Object.keys(updateFields).map(item => {
      let currentValue = updateFields[currentKey];
      let syncValue = currentValue.value[-currentKey];
      if (gotoSync.includes(item)) {
        updateFields[item].value[item] = currentValue.value[currentKey];
        if (syncValue) {
          updateFields[item].value[-item] = [...syncValue];
        }
      }
    })
    detailSettingForm.updateFields(updateFields)
  }


  getFields() {
    const { homeStore } = this.props;
    const { detailSettingForm } = homeStore;
    const { conditioninfo, isInit } = detailSettingForm;
    const fields = [];
    if (isInit) {
      toJS(conditioninfo).forEach((group) => {
        toJS(group.items).forEach((field) => {
          // 新到达
          if (field.domkey[0] == group.newArrivalKey) {
            fields.push(
              <div
                onClick={() => {
                  const { homeStore } = this.props;
                  homeStore.dataChange = true;
                }}
                key={field.domkey.join('__')}>
                <Form.Item
                  key={field.domkey.join('__')}
                  form={detailSettingForm}
                  fieldConfig={field}
                  onChange={detailSettingForm.onChange}
                />
                <div className="sync-button">
                  <Button icon="blog-huxiangguanzhu" type="ghost" className="am-button-borderfix"
                    onClick={this.syncClick.bind(this)}
                  >{getLabel("19015", '同步')}</Button>
                </div>
                {group.options.map(item => {
                  const valueArray = group.value.split(",")
                  // console.log(group.value, item.key, valueArray.includes(item.key))
                  return (
                    <CheckboxItem key={item.key} checked={valueArray.includes(item.key)}
                      onChange={(e) => {
                        homeStore.dataChange = true;
                        if (valueArray.includes(item.key)) {
                          const spliceIndex = valueArray.indexOf(item.key);
                          valueArray.splice(spliceIndex, 1);
                        } else {
                          valueArray.push(item.key);
                        }
                        conditioninfo[0].value = valueArray.join();
                      }}
                    > {item.showname} </CheckboxItem>
                  )
                })}
              </div>);
          } else {
            fields.push(
              <div
                onClick={() => {
                  const { homeStore } = this.props;
                  homeStore.dataChange = true;
                }}
                key={field.domkey.join('__')}>
                <Form.Item
                  key={field.domkey.join('__')}
                  form={detailSettingForm}
                  fieldConfig={field}
                  onChange={detailSettingForm.onChange}
                />
                {/* 43	流程完成提醒、流程超时提醒下，没有同步按钮	截图 '!A1367	2020/8/3	*/}
                {field.domkey[0].includes("-") && (
                  <div className="sync-button">
                    <Button icon="blog-huxiangguanzhu" type="ghost" className="am-button-borderfix"
                      onClick={this.syncClick.bind(this)}
                    >同步</Button>
                  </div>
                )}
              </div>);
          }
        });
      });
    }
    return fields;
  }

  bottomSave() {
    const { homeStore, prefixCls, history } = this.props;
    const { detailSetting, detailSettingForm } = homeStore;
    const result = detailSettingForm.doValidate();
    // console.log(result)
    if (result.pass) {
      if (detailSetting.otherParams.detatilType === "2") {
        homeStore.saveWorkflowDetail()
      } else {
        homeStore.saveDetailConfig()
      }
      // history.goBack();
    }
  }

  render() {
    const { homeStore, prefixCls, history } = this.props;
    const { detailSetting, detailSettingForm } = homeStore;
    const tabs = detailSettingForm.conditioninfo[0] &&
      detailSettingForm.conditioninfo[0].items.length &&
      detailSettingForm.conditioninfo[0].items.map(item => {
        return {
          title: item.label,
          index: item.domkey[0]
        }
      });

    let tabIndex = 0;
    tabs && tabs.map((item, index) => { item.index === detailSetting.tabIndex ? tabIndex = index : 0; });
    return (
      <div className={`${prefixCls}-modal`} style={{ paddingBottom: 94 }}>
        <BreadCrumb
          breadName={detailSetting.title}
          breadLevel={3}
        />
        <div className={`${prefixCls}-modal-content`}>
          <Form>
            <List>
              <Tabs
                initialPage={tabIndex}
                animated={false}
                tabs={tabs}
                renderTabBar={props => <Tabs.ExpandTabBar {...props} />}
                // onChange={(tab, index) => { console.log('onChange', index, tab); }}
                onTabClick={(tab, index) => {
                  detailSetting.tabTitle = tab.title;
                  detailSetting.tabIndex = tab.index;
                }}
              >
                {this.getFields()}
              </Tabs>
            </List>
          </Form>
        </div>
        <Button type="primary" className="" onClick={this.bottomSave} >{getLabel("30986", "保存")}</Button>
        <Modal
          transparent
          visible={detailSetting.syncModal}
          footer={[
            { text: getLabel("31129", "取消"), onPress: () => { detailSetting.syncModal = false; } },
            { text: getLabel("33703", "确认"), onPress: () => { detailSetting.syncModal = false; this.syncConfirm(); } },
          ]}
          title={getLabel("389163", "将所选路径同步到")}
        >
          <div>
            <List>
              {detailSettingForm.conditioninfo[0] && detailSettingForm.conditioninfo[0].syncOptions &&
                detailSettingForm.conditioninfo[0].syncOptions
                  .filter(item => item.showname != detailSetting.tabTitle)
                  .map(item => {
                    return (
                      <CheckboxItem
                        onChange={(e) => {
                          const group = detailSettingForm.conditioninfo[0];
                          const valueArray = group.syncValue.split(",")
                          if (group.syncValue.includes(item.key)) {
                            const spliceIndex = valueArray.indexOf(item.key);
                            valueArray.splice(spliceIndex, 1);
                          } else {
                            valueArray.push(item.key);
                          }
                          detailSettingForm.conditioninfo[0].syncValue = valueArray.join();

                        }}
                        checked={detailSettingForm.conditioninfo[0].syncValue.includes(item.key)}
                        key={item.key}>
                        {item.showname}
                      </CheckboxItem>
                    )
                  })}
            </List>

          </div>
        </Modal>
      </div>
    )
  }
}
